var eventproxy = require('eventproxy');
var superagent = require('superagent');
var cheerio = require('cheerio');
var url = require('url');

var cnodeUrl = 'https://cnodejs.org/';

superagent.get(cnodeUrl)
  .end(function (err, res) {
    if (err) {
      return console.error(err);
    }
    var topicUrls = [];
    var $ = cheerio.load(res.text);
    $('#topic_list .topic_title').each(function (idx, element) {
      var $element = $(element);
      var href = url.resolve(cnodeUrl, $element.attr('href'));
      topicUrls.push(href);
    });

    var ep = new eventproxy();

    ep.after('topic_html', topicUrls.length, function (topics) {
      topics.map(function (topicPair) {
        console.log(topicPair[1]);
      });
    });


    topicUrls.forEach(function (topicUrl) {
      superagent.get(topicUrl)
        .end(function (err, res) {
          if (err) {
            return console.error(err);
          }
          console.log('fetch ' + topicUrl + ' successful');
          var $ = cheerio.load(res.text);
          var comment1 = $('.reply_content').eq(0).text().trim();
          var content = {
            title: $('.topic_full_title').text().trim(),
            href: topicUrl,
            comment1: '',
            auth1: '',
            score1: ''
          };
          if (comment1) {
            content["comment1"] = comment1;
            content["auth1"] = $('.user_avatar').eq(0).find('img').attr('title');
            var authUri = url.resolve(cnodeUrl, $('.user_avatar').eq(0).attr('href'));
            superagent.get(authUri)
              .end(function (err, res) {
                console.log('fetch ' + authUri + ' successful');
                var $ = cheerio.load(res.text);
                content["score1"] = $('.user_profile ul span.big').text().trim();
                ep.emit('topic_html', [topicUrl, content]);
              });
          } else {
            ep.emit('topic_html', [topicUrl, content]);
          }
        });
    });
  });

